package com.stars.easyms.datasource.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Set;

/**
 * <p>className: EasyMsClassPathMapperScanner</p>
 * <p>description: ClassPathMapperScanner自定义实现类</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-05-08 10:27
 */
@Slf4j
final class EasyMsClassPathMapperScanner extends ClassPathMapperScanner {

    private ApplicationContext applicationContext;

    private Class<? extends Annotation> annotationClass;

    EasyMsClassPathMapperScanner(ApplicationContext applicationContext, BeanDefinitionRegistry registry) {
        super(registry);
        this.applicationContext = applicationContext;
    }

    @Override
    public void setAnnotationClass(Class<? extends Annotation> annotationClass) {
        this.annotationClass = annotationClass;
        super.setAnnotationClass(annotationClass);
    }

    @Override
    public Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
        if (beanDefinitions.isEmpty()) {
            log.warn("No Repository with annotation '{}' was found in '{}' package. Please check your configuration.", annotationClass.getSimpleName(), Arrays.toString(basePackages));
        } else {
            beanDefinitions.forEach(beanDefinitionHolder -> {
                try {
                    applicationContext.getBean(beanDefinitionHolder.getBeanName());
                } catch (BeansException e) {
                    log.error("Unable to get bean '{}'!", beanDefinitionHolder.getBeanName());
                }

            });
        }
        return beanDefinitions;
    }
}